package org.ctstudio.oa.duty.config;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

@Configuration
@EnableTransactionManagement
@ComponentScan(basePackages = { "org.ctstudio.oa.duty.web" })
// @ServletComponentScan("org.ctstudio.oa.duty.web")
@AutoConfigureAfter(ContextConfig.class)
public class ServletConfig extends WebMvcConfigurerAdapter {
  @Bean(name = "messageSource")
  public ReloadableResourceBundleMessageSource getMessageSource() {
    ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
    messageSource.setBasename("classpath:i18n/errMsg");
    return messageSource;
  }

  @Override
  public void addInterceptors(InterceptorRegistry registry) {
    super.addInterceptors(registry);
    registry.addInterceptor(new HandlerInterceptorAdapter() {
      @Override
      public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println(handler.getClass().getName());
        return super.preHandle(request, response, handler);
      }
    }).addPathPatterns("/**").excludePathPatterns("/manager/");
  }

  @ExceptionHandler(Throwable.class)
  @ResponseBody
  String handleControllerException(HttpServletRequest request, Throwable ex) {
    // HttpStatus status = getStatus(request);
    return ex.getMessage();
  }
}
